package com.yeyks.config;

import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Objects;
import java.util.Set;

/**
 * 路由配置文件读取
 * @author: gui
 * @date: 2019/6/18 0018 11:28
 */
@Component
@Slf4j
public class PermitUrlConfiguration {

    @Value("${permit.url}")
    private String permitUrl;

    /**
     * 不需要鉴权过滤的url
     */
    private String[] permitUrlArray;


    @PostConstruct
    public void init(){

        String[] itemPermitUrlArray = null;
        if(!StringUtils.isEmpty(permitUrl)){
            itemPermitUrlArray = permitUrl.split(",");
        }
        //去掉空格
        if(null != itemPermitUrlArray && itemPermitUrlArray.length > 0){
            for(int i = 0; i < itemPermitUrlArray.length; i ++){
                itemPermitUrlArray[i] = (itemPermitUrlArray[i]).trim();
            }
        }
        //删除空的String
        Set<String> itemPermitUrlSet = Sets.newHashSet(Arrays.asList(Objects.requireNonNull(itemPermitUrlArray)));
        if(!CollectionUtils.isEmpty(itemPermitUrlSet)){
            itemPermitUrlSet.removeIf(eachItemPermitUrl -> null == eachItemPermitUrl || eachItemPermitUrl.trim().length() <= 0);
            //转数组
            permitUrlArray = itemPermitUrlSet.toArray(new String[itemPermitUrlSet.size()]);
        }

        if(null == permitUrlArray || permitUrlArray.length <= 0){
            log.error("直接通过鉴权的url为空");
        }
    }

    public String[] getPermitUrlArray(){
        return permitUrlArray;
    }
}
